import { prisma } from "@/lib/prisma"
import { getServerSession } from "next-auth"
import { NextResponse } from "next/server"
import { authOptions } from "@/lib/auth"

function calculateTimeDifference(date1: Date, date2: Date): number {
  return Math.abs(date1.getTime() - date2.getTime())
}

export async function POST(req: Request) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ error: "未授权访问" }, { status: 401 })
    }

    const { eventId, targetDate, allEventIds } = await req.json()
    const targetDateTime = new Date(targetDate)

    // 获取所有事件
    const events = await prisma.event.findMany({
      where: { id: { in: allEventIds } }
    })

    // 计算每个事件与目标日期的时间差
    const eventsWithDiff = events.map(event => {
      const eventDate = new Date(event.date)
      const timeDiff = calculateTimeDifference(targetDateTime, eventDate)
      const yearDiff = Math.abs(targetDateTime.getFullYear() - eventDate.getFullYear())
      const dayDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24)) % 365

      return {
        eventId: event.id,
        date: event.date,
        timeDiff,
        yearDiff,
        dayDiff,
        isSelected: event.id === eventId
      }
    })

    // 按时间差排序
    eventsWithDiff.sort((a, b) => a.timeDiff - b.timeDiff)

    // 获取最大和最小时间差
    const minDiff = eventsWithDiff[0].timeDiff
    const maxDiff = eventsWithDiff[eventsWithDiff.length - 1].timeDiff
    const diffRange = maxDiff - minDiff

    // 计算每个事件的得分
    const results = eventsWithDiff.map(event => {
      // 使用线性插值计算分数（0-10分）
      const score = Math.round(
        10 - ((event.timeDiff - minDiff) / diffRange) * 10
      )

      return {
        eventId: event.eventId,
        date: event.date,
        score,
        yearDiff: event.yearDiff,
        dayDiff: event.dayDiff,
        isSelected: event.isSelected
      }
    })

    return NextResponse.json({ 
      results,
      correctAnswerId: eventsWithDiff[0].eventId,  // 时间差最小的为最佳答案
      selectedScore: results.find(r => r.isSelected)?.score || 0
    })

  } catch (error) {
    console.error("Select answer error:", error)
    return NextResponse.json(
      { error: "提交答案失败" },
      { status: 500 }
    )
  }
} 